package com.cckj.projectapi.framework.advice;

import com.cckj.common.response.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
  * @Description //TODO  统一返回值处理
  * @Author wjq
  * @time: 2020/11/3 10:48
  */
@ControllerAdvice(basePackages = "com.domain.projectapi")
@Slf4j
public class ResultControllerAdvice implements ResponseBodyAdvice<Object> {

  // 是否支持 advice 功能，ture 支持  false 不支持
  @Override
  public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
    return true;
  }

  // 对controller 返回值进行统一处理，请求抛出的异常数据也会经过这里
  @Override
  public Object beforeBodyWrite(Object o, MethodParameter methodParameter,
                                MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
                                ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
    MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(o);
    if (o instanceof ResultData){
      mappingJacksonValue.setValue(o);
    } else {
      mappingJacksonValue.setValue(ResultData.ok(o));
    }
    return mappingJacksonValue;
  }

}